<script setup>
import { postAddPost } from '@/axios/api/posts'
import LfButton from '@/components/commonUI/LfButton.vue'
import LfImageUpload from '@/components/commonUI/LfImageUpload.vue'
import LfInput from '@/components/commonUI/LfInput.vue'
import LfTabs from '@/components/commonUI/LfTabs.vue'
import LfTextArea from '@/components/commonUI/LfTextArea.vue'
import { useLastPostListQuery, useUserPostsQuery } from '@/composables/usePostDataQuery'
import { useMutation } from '@tanstack/vue-query'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import RichTextEditor from './components/RichTextEditor.vue'
import SubmitSelectTopic from './components/SubmitSelectTopic.vue'
import SubmitSuccess from './components/SubmitSuccess.vue'
import { postUploadFile } from '@/axios/api/upload'
import { useAddArticleMutation } from '@/composables/usePostDataQuery'
import { useGlobalStore } from '@/stores/globalStore'
import SubmitSelectDiscuss from './components/SubmitSelectDiscuss.vue'
import VoteSubmit from './components/VoteSubmit.vue'

import { useRouter } from 'vue-router'

const router = useRouter()


const topicList = [
  { id: 3, name: '文章', type: '3' },
  // { id: 5, name: '问题', type: '5' },
  { id: 1, name: '图文', type: '1' },
  { id: 2, name: '视频', type: '2' },
  { id: 4, name: '投票', type: '4' },
]

const globalStore = useGlobalStore()

const postFilter = computed(() => globalStore.postFilter)

const { refetch: refetchLastPostList } = useLastPostListQuery(postFilter)
const { refetch: refetchUserPosts } = useUserPostsQuery(postFilter)

const addArticleMutate = useAddArticleMutation()

const topicId = ref(undefined)
const discussId = ref(undefined)
const selectedDiscussName = ref(undefined)

const valueHtml = ref('')

const previewVideo = ref(undefined)
const uploadVideo = ref(undefined)

const voteComponentRef = ref(null)

const uploadRef = ref(null)
const coverUploadRef = ref(null)
const activeIndex = ref(0)

const title = ref(undefined)
const content = ref(undefined)

const errorMsg = ref(undefined)

const showSuccess = ref(false)
const isSubmitting = ref(false)

const questionType = ref(undefined)
const questionTypeList = [
  { value: 'general', label: '常规问题' },
  { value: 'urgent', label: '紧急问题' },
  { value: 'suggestion', label: '建议' },
]

const changeSubmitType = (value) => {
  activeIndex.value = value
}

const handleTopicClick = (id, name) => {
  topicId.value = id
  // 清除讨论
  discussId.value = undefined
  selectedDiscussName.value = undefined
}

const handleDiscussClick = (id, name) => {
  selectedDiscussName.value = name
  discussId.value = id
}

const handleSubmit = () => {
  // 防止重复提交
  if (isSubmitting.value) return
  
  // 设置提交中状态
  isSubmitting.value = true

  if (activeIndex.value == 3) {
    // 投票提交特殊处理
    try {
      voteSubmit()
    } finally {
      // 重置提交状态
      setTimeout(() => {
        isSubmitting.value = false
      }, 500)
    }
    return
  }

  if (!verify()) {
    // 验证失败时重置状态
    isSubmitting.value = false
    return
  }

  if (activeIndex.value == 0) {
    // 文章：上传封面
    coverUploadRef.value.uploadImg((res) => {
      articleSubmit(res)
      // 重置提交状态
      setTimeout(() => {
        isSubmitting.value = false
      }, 500)
    })
  } else if (activeIndex.value == 2) {
    // 视频
    if (!uploadVideo.value) {
      errorMsg.value = '请上传视频'
      isSubmitting.value = false
      return
    }

    uploadFileApi((res) => {
      postSubmit([res])
      // 重置提交状态
      setTimeout(() => {
        isSubmitting.value = false
      }, 500)
    })
  } else if (activeIndex.value === 1) {
    // 图文：上传图片
    uploadRef.value.uploadImg((res) => {
      console.log(res)
      articlePicSubmit(res)
      // 重置提交状态
      setTimeout(() => {
        isSubmitting.value = false
      }, 500)
    })
  } else {
    // 其他情况重置状态
    isSubmitting.value = false
  }
}

const verify = () => {
  if (topicId.value == undefined) {
    errorMsg.value = '请选择主题'
    return false
  }
  // if (activeIndex.value === 1 && questionType.value === undefined) {
  //   errorMsg.value = '请选择问题类型'
  //   return false
  // }
  if (!title.value || !title.value.trim()) {
    errorMsg.value = '请输入标题'
    return false
  }
  // 文章/提问页签内容校验
  if ((activeIndex.value == 0) && (!valueHtml.value || !valueHtml.value.replace(/<[^>]+>/g, '').trim())) {
    // if ((activeIndex.value === 0 || activeIndex.value === 1) && (!valueHtml.value || !valueHtml.value.replace(/<[^>]+>/g, '').trim())) {
    errorMsg.value = '请输入内容'
    return false
  }
  // 图文页签内容校验
  if (activeIndex.value == 1 && (!content.value || !content.value.trim())) {
    // if (activeIndex.value === 2 && (!content.value || !content.value.trim())) {
    errorMsg.value = '请输入内容'
    return false
  }
  return true
}

const mutation = useMutation({
  mutationFn: (data) => postAddPost(data),
  onSuccess: (res) => {
    if (res.code === 500) {
      return
    }

    submitSuccessCallback()
  },
  onError: (error) => {
    errorMsg.value = error.msg || '提交失败，请重试'
  },
})

const articleSubmit = (resImgs) => {
  addArticleMutate.mutate(
    {
      title: title.value,
      content: valueHtml.value,
      media: resImgs ? resImgs : undefined,
      topicId: topicId.value,
      type: topicList[activeIndex.value].type,
      discussId: discussId.value,
      questionType: questionType.value,
    },
    {
      onSuccess: (res) => {
        if (res.code === 500) {
          return
        }

        submitSuccessCallback()
      },
    },
  )
}

const articlePicSubmit = (resImgs) => {
  addArticleMutate.mutate(
    {
      title: title.value,
      content: content.value,
      media: resImgs ? resImgs : undefined,
      topicId: topicId.value,
      type: topicList[activeIndex.value].type,
      discussId: discussId.value,
      questionType: questionType.value,
    },
    {
      onSuccess: (res) => {
        if (res.code === 500) {
          return
        }

        submitSuccessCallback()
      },
    },
  )
}

const postSubmit = (resImgs) => {
  mutation.mutate({
    title: title.value,
    content: content.value,
    topicId: topicId.value,
    type: topicList[activeIndex.value].type,
    cut: 0,
    media: resImgs,
    discussId: discussId.value,
    questionType: questionType.value,
  })
}

const handleInputChange = (e) => {
  title.value = e.target.value
}

const handleTextAreaChange = (e) => {
  content.value = e.target.value
}

const readAndUploadVideo = (e) => {
  const file = e.target.files[0]
  uploadVideo.value = file

  const reader = new FileReader()

  // 监听文件读取完成事件
  reader.onload = function (event) {
    previewVideo.value = event.target.result // 添加到预览数组
  }

  // 读取文件为Base64字符串
  reader.readAsDataURL(file)
}

const handleUploadVideo = () => {
  const input = document.getElementById('videoUpload')
  input.click()
}

const uploadFileApi = (callback) => {
  const formData = new FormData()
  formData.append('Image', uploadVideo.value)

  postUploadFile(formData).then((res) => {
    // console.log(res)
    if (res.code === 500) {
      return
    }
    callback(res.result)
  })
}

const submitSuccessCallback = () => {
  // 刷新帖子列表
  setTimeout(() => {
    refetchLastPostList()
    refetchUserPosts()
  }, 1000)

  router.push('/submitSuccess')

  // showSuccess.value = true
}

const voteSubmit = () => {
  voteComponentRef.value.submitVote()
}
</script>

<template>
  <SubmitSuccess v-if="showSuccess" />
  <div v-else class="p-4 flex flex-col gap-4 max-w-[1400px] mx-auto ">
    <div class="flex justify-between">
      <div class="flex gap-6 items-end">
        <div class="text-[28px] font-medium">创建新帖</div>
        <SubmitSelectTopic :onTopicClick="handleTopicClick" />
        <!-- v-if="topicId && activeIndex !== 4" -->

        <SubmitSelectDiscuss v-if="topicId && activeIndex !== 3" :selectedDiscussName="selectedDiscussName"
          :onDiscussClick="handleDiscussClick" :topicId="topicId" />
      </div>
      <LfButton type="primary" @click="handleSubmit" :errorMsg="errorMsg" :disabled="isSubmitting">发布</LfButton>
      <!-- 如果不兼容恢复以前 -->
      <!-- <LfButton type="primary" :onClick="handleSubmit" :errorMsg="errorMsg">发布</LfButton> -->
    </div>

    <LfTabs :activeIndex="activeIndex" :tabOptions="topicList" :onTopicClick="changeSubmitType" />

    <!-- 只有提问页签显示问题类型选择 -->


    <!-- 文章 -->
    <template v-if="activeIndex == 0">
      <LfInput placeholder="标题" :onChange="handleInputChange" />
      <LfImageUpload ref="coverUploadRef" :maxCount="1" title="上传封面" />
      <RichTextEditor v-model="valueHtml" />
    </template>

    <!-- <template v-if="activeIndex === 1">
      <LfInput placeholder="标题" :onChange="handleInputChange" />
      <el-select
      v-model="questionType"
      placeholder="请选择问题类型"
      clearable
      class="w-60 mb-2"
    >
      <el-option
        v-for="item in questionTypeList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
      <RichTextEditor v-model="valueHtml" />
    </template> -->
    <!-- 图文 -->
    <div v-if="activeIndex == 1" class="flex flex-col gap-4">
      <!-- <div v-if="activeIndex === 2" class="flex flex-col gap-4"> -->
      <LfInput placeholder="标题" :onChange="handleInputChange" />
      <LfTextArea :onChange="handleTextAreaChange" />
      <LfImageUpload ref="uploadRef" />
    </div>

    <!-- 视频 -->
    <div v-if="activeIndex == 2" class="flex flex-col gap-4">
      <!-- <div v-if="activeIndex === 3" class="flex flex-col gap-4"> -->
      <LfInput placeholder="标题" :onChange="handleInputChange" />
      <LfTextArea :onChange="handleTextAreaChange" />
      <div>
        <div @click="handleUploadVideo" class="lf-btn-box px-3">上传视频</div>
        <input type="file" :onchange="readAndUploadVideo" id="videoUpload" accept="video/*" />
      </div>
      <div v-if="previewVideo">
        <video :src="previewVideo" controls class="w-[300px]" />
      </div>
    </div>

    <!-- 投票 -->
    <div v-if="activeIndex == 3" class="flex flex-col gap-4">
      <!-- <div v-if="activeIndex === 4" class="flex flex-col gap-4"> -->
      <VoteSubmit ref="voteComponentRef" :topicId="topicId" :discussId="discussId"
        :onSubmitSuccess="submitSuccessCallback" />
    </div>
  </div>
</template>

<style scoped lang="scss"></style>
